package org.dandelion.papercheck.config;


import org.dandelion.papercheck.annotation.AdminRequired;
import org.dandelion.papercheck.annotation.PassToken;
import org.dandelion.papercheck.annotation.UserLoginToken;
import org.dandelion.papercheck.annotation.VIPRequired;
import org.dandelion.papercheck.util.JWTUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


public class AuthenticationInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        logger.info("request uri: " + httpServletRequest.getRequestURI());

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            return true;
        }
        // 检查UserManagement注释
        if (method.isAnnotationPresent(VIPRequired.class)) {
            VIPRequired vipRequired = method.getAnnotation(VIPRequired.class);
            if (vipRequired.required()) {
                if (token == null) {
                    httpServletRequest.getRequestDispatcher("/logout")
                            .forward(httpServletRequest, httpServletResponse);
                    return false;
                } else {
                    try {
                        JWTUtils.verify(token);
                    } catch (Exception e) {
                        httpServletRequest.getRequestDispatcher("/JwtError")
                                .forward(httpServletRequest, httpServletResponse);
                        return false;
                    }
                    if (!JWTUtils.getVIP(httpServletRequest).equals("true")) {
                        httpServletRequest.getRequestDispatcher("/illegalAuthority")
                                .forward(httpServletRequest, httpServletResponse);
                        return false;
                    }
                }
            }
        }
        if (method.isAnnotationPresent(AdminRequired.class)) {
            AdminRequired adminRequired = method.getAnnotation(AdminRequired.class);
            if (adminRequired.required()) {
                if (token == null) {
                    httpServletRequest.getRequestDispatcher("/logout").forward(httpServletRequest, httpServletResponse);

                    return false;
                } else {
                    try {
                        JWTUtils.verify(token);
                    } catch (Exception e) {
                        httpServletRequest.getRequestDispatcher("/JWTerror").forward(httpServletRequest, httpServletResponse);
                        return false;
                    }
                    if (!JWTUtils.getAdmin(httpServletRequest).equals("true")) {
                        httpServletRequest.getRequestDispatcher("/illegalAuthority").forward(httpServletRequest, httpServletResponse);

                        return false;
                    }
                }
            }
        }
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    httpServletRequest.getRequestDispatcher("/logout").forward(httpServletRequest, httpServletResponse);

                    return false;
                } else {
                    try {
                        JWTUtils.verify(token);
                    } catch (Exception e) {
                        httpServletRequest.getRequestDispatcher("/JWTerror").forward(httpServletRequest, httpServletResponse);

                        return false;
                    }
                }
            }
        }

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
